package com.example.graduation.exception;

import lombok.extern.slf4j.Slf4j;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * ProjectName graduation
 * 全局统一异常处理
 *
 * @author xieyucan
 * <br>CreateDate 2022/2/11 14:50
 */
@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {

    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler
    public String exceptionHandler(Exception e) {
        log.error("执行异常");
        if (e instanceof MyException) {
            MyException exception = (MyException) e;
            return exception.getMsg();
        } else if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            return exception.getBindingResult().getFieldError().getDefaultMessage();
        } else if (e instanceof UnauthorizedException) {
            return "您不具备相关权限";
        } else {
            return "后端执行异常☺";
        }
    }
}
